/*
 * Copyright 2022 learn-netty4 Project
 *
 * The learn-netty4 Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.jxw.cloudpen.web.netty.websocketserver;

import cn.hutool.json.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.api.client.json.Json;
import com.jxw.cloudpen.web.netty.Entity.StreamData;
import com.jxw.cloudpen.web.netty.common.CommonRpcDecoderHandler;
import com.jxw.cloudpen.web.netty.common.CommonRpcEncoderHandler;
import com.jxw.cloudpen.web.netty.common.LocalSession;
import com.jxw.cloudpen.web.netty.common.SessionManger;
import com.jxw.cloudpen.web.netty.google.InfiniteStreamRecognize6;
import com.jxw.cloudpen.web.netty.google.StreamRecognManager;
import com.jxw.cloudpen.web.netty.handler.BusinHandler;
import com.jxw.cloudpen.web.netty.handler.ConnectionHandler;
import com.jxw.cloudpen.web.netty.handler.LoginRequestHandler;
import com.jxw.cloudpen.web.netty.util.ByteObjUtil;
import com.jxw.cloudpen.web.netty.util.ByteUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.*;

/**
 * 同时处理消息和
 */
@Slf4j
public class TestSocketServerHandler extends SimpleChannelInboundHandler<Object> {

    private static final String WEBSOCKET_PATH = "/websocket";

    private WebSocketServerHandshaker handshaker;
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws IOException {
        //根据消息类型，处理两种不同的消息
//        log.info("msg is {} ",JSONObject.toJSONString(msg));
        if (msg instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        } else if (msg instanceof WebSocketFrame) {
            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws IOException {
        // 处理异常
        if (!req.decoderResult().isSuccess()) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(req.protocolVersion(), BAD_REQUEST,
                                                                   ctx.alloc().buffer(0)));
            return;
        }

        // 只允许get请求
        if (!GET.equals(req.method())) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(req.protocolVersion(), FORBIDDEN,
                                                                   ctx.alloc().buffer(0)));
            return;
        }

        // websocket握手
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                getWebSocketLocation(req), null, true, 50 * 1024 * 1024);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        StreamData streamData = new StreamData();
//        streamData.setClientId(uuid);
        streamData.setClientId( "f544f5209e7d4f59a82ba3a780736faf");
        ByteBuf responseBuffer = ctx.alloc().buffer();
        responseBuffer.writeBytes( JSONObject.toJSONString(streamData).getBytes(StandardCharsets.UTF_8));
        ctx.channel().writeAndFlush(new TextWebSocketFrame(responseBuffer));
    }

    private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // 处理各种websocket的frame信息
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        if (frame instanceof PingWebSocketFrame) {
            ctx.write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        if (frame instanceof TextWebSocketFrame) {
            // 直接返回
            //此处理
            ctx.write(frame.retain());
            return;
        }
        if (frame instanceof BinaryWebSocketFrame) {
            //解析
            ByteBuf content = frame.content();
            byte[] byteArray = new byte[content.readableBytes()];
            content.readBytes(byteArray);

//            System.out.println("Received binary data: " + Arrays.toString(byteArray));
//            // 直接返回
//            ByteBuf responseBuffer = ctx.alloc().buffer();
//
//            responseBuffer.writeBytes( "ssss".getBytes(StandardCharsets.UTF_8));
////            responseBuffer.writeBytes(ByteObjUtil.objToBytes("sssssssss"));
//            ctx.channel().writeAndFlush(new TextWebSocketFrame(responseBuffer));

            executeBusin(byteArray,ctx);


//            executorService.submit(()-> {
//                try {
//                    InfiniteStreamRecognize6 infiniteStreamRecognize6 = new InfiniteStreamRecognize6();
//                    StreamRecognManager.map.put(session.getClientId(),infiniteStreamRecognize6);
//                    infiniteStreamRecognize6.infiniteStreamingRecognize( "en-US");
////                InfiniteStreamRecognize6.infiniteStreamingRecognize( "en-US");
//                } catch (Exception e) {
//                    System.out.println("Exception caught: " + e);
//                }
//            });




        }
    }

    private void executeBusin(byte[] byteArray,ChannelHandlerContext ctx){

        StreamData streamData = (StreamData) ByteObjUtil.bytesToObject(byteArray);

        if(streamData.getType() ==1){
            //打开通道
//            executorService.submit(()-> {
//                try {
//                    InfiniteStreamRecognize6 infiniteStreamRecognize6 = new InfiniteStreamRecognize6(ctx);
//                    StreamRecognManager.map.put(streamData.getClientId(),infiniteStreamRecognize6);
//                    infiniteStreamRecognize6.infiniteStreamingRecognize( "en-US");
////                InfiniteStreamRecognize6.infiniteStreamingRecognize( "en-US");
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    System.out.println("Exception caught: " + e);
//                }
//            });
        }else if(streamData.getType() ==2){
            //执行识别
//            InfiniteStreamRecognize6 infiniteStreamRecognize6 = StreamRecognManager.map.get(streamData.getClientId());
//            try {
//                infiniteStreamRecognize6.sharedQueue.put(streamData.getData());
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }


            streamData = new StreamData();
//        streamData.setClientId(uuid);
            streamData.setClientId( "f544f5209e7d4f59a82ba3a780736faf");
            ByteBuf responseBuffer = ctx.alloc().buffer();
            responseBuffer.writeBytes( JSONObject.toJSONString(streamData).getBytes(StandardCharsets.UTF_8));
            ctx.channel().writeAndFlush(new TextWebSocketFrame(responseBuffer));
        }
    }

    private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
        // 生成错误页面
        HttpResponseStatus responseStatus = res.status();
        if (responseStatus.code() != 200) {
            ByteBufUtil.writeUtf8(res.content(), responseStatus.toString());
            HttpUtil.setContentLength(res, res.content().readableBytes());
        }
        // 发送response
        boolean keepAlive = HttpUtil.isKeepAlive(req) && responseStatus.code() == 200;
        HttpUtil.setKeepAlive(res, keepAlive);
        ChannelFuture future = ctx.write(res);
        if (!keepAlive) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 异常处理
        log.error("出现异常",cause);
        ctx.close();
    }

    private static String getWebSocketLocation(FullHttpRequest req) {
        String location =  req.headers().get(HttpHeaderNames.HOST) + WEBSOCKET_PATH;
            return "ws://" + location;
    }
}
